package cn.itcast.demo.lock;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;

/**
 * @author 虎哥
 */
public class ReentrantRedisLock implements RedisLock {

    private String key;

    private StringRedisTemplate redisTemplate;

    public ReentrantRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    private static final String VALUE_PREFIX = UUID.randomUUID().toString() + "-";

    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    private static final DefaultRedisScript<Object> UNLOCK_SCRIPT;

    static {
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setLocation(new ClassPathResource("lock.lua"));
        LOCK_SCRIPT.setResultType(Long.class);

        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
    }

    private String releaseTime;

    @Override
    public boolean tryLock(long releaseTime) {
        this.releaseTime = String.valueOf(releaseTime);
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        Long num = redisTemplate.execute(LOCK_SCRIPT, Collections.singletonList(key), value, this.releaseTime);
        return num != null && num == 1;
    }

    @Override
    public void unlock() {
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key), value, this.releaseTime);
    }
}
